package org.hairball.vis;

import org.hairball.graph.EdgeVisitor;
import org.hairball.graph.HairballGraph;
import org.hairball.graph.NodeVisitor;

public class DotGraphCreator implements GraphMarkupCreator {
    public DotGraphCreator() {

    }

    public String createFromGraph(String graphName, HairballGraph graph) {
        String header = "digraph \"" + graphName + "\" {\n";
        String footer = "}";
        String nodeDelcarations = createNodeDeclarations(graph);
        String edgeDeclarations = createEdgeDeclarations(graph);
        return header + nodeDelcarations + edgeDeclarations + footer;
    }

    private String createEdgeDeclarations(HairballGraph graph) {
        final StringBuilder builder = new StringBuilder();
        graph.visitEdges(new EdgeVisitor() {

            public void visit(String fromNode, String toNode, String edgeType) {
                builder.append("\"").append(fromNode).append("\" -> \"").append(toNode).append("\" ");
                builder.append("[ label = \"").append(edgeType).append("\" ];\n");
            }
        });

        return builder.toString();
    }

    private String createNodeDeclarations(HairballGraph graph) {
        final StringBuilder builder = new StringBuilder();

        graph.visitNodes(new NodeVisitor() {
            public void visit(String node, boolean connected) {
                builder.append("\"").append(node).append("\"");
                builder.append(" [shape=box, height=0.75];\n");
            }
        });

        return builder.toString();
    }
}
